//
//  TKIMChartView.m
//  TKIM
//
//  Created by liupm on 15/7/27.
//  Copyright (c) 2015年 liupm. All rights reserved.
//

#import "TKIMChatView.h"
#import "TKIMAudioMsgView.h"
#import "TKIMTableView.h"
#import "TKIMRefreshHeaderView.h"
#import "TKIMAcceptOrderTip.h"
#import "TKIMKeFuMenuView.h"

@interface
    TKIMChatView()<UITableViewDataSource,UITableViewDelegate,TKIMToolBarDelegate,TKIMAudioDelegate,TKIMTableViewDelegate,UIActionSheetDelegate>
@property(nonatomic,strong) NSMutableArray *dataSource;//数据源

@property(nonatomic,strong) TKIMAudioHelper *audioHelper;//声音工具对象
@property(nonatomic,strong) TKIMAudioMsgView *currentAudio;//当前声音播放的对象
@property (strong, nonatomic) NSDate *chatTagDate;
@property(strong,nonatomic) TKIMMessage *selectMessage;
@property(nonatomic,strong) TKIMMenuBar *menuBar;//工具栏
@property(nonatomic,assign) TKIMToolBarType toolBarType;
@property(nonatomic,strong) UIButton * deleteBtn;  //删除按钮
@property(nonatomic,strong) NSDictionary *emotion;
@property (nonatomic,strong)TKIMRefreshHeaderView * refreshHeader;
@property(nonatomic,weak)TKIMAcceptOrderTip * tip;

@property(nonatomic,assign) BOOL isNeedGoBootom;

@property (nonatomic,strong)dispatch_queue_t  messageQueue;;
@end


@implementation TKIMChatView
{
    // dispatch_queue_t _messageQueue;
}

-(instancetype)initWithFrame:(CGRect)frame channel:(NSUInteger)channel type:(TKIMToolBarType)toolBarType
{
    self = [super initWithFrame:frame];
    if (self) {
        _audioHelper = [[TKIMAudioHelper alloc] init];
        _audioHelper.delegate = self;
        _dataSource = [NSMutableArray array];
        _messageQueue = dispatch_queue_create("com.thinkive.message", NULL);
        _iskefu = true;
        if (channel == 2) {
            _iskefu = false;
        }
        _toolBarType = toolBarType;
        [self drawView:_iskefu];
        _isNeedGoBootom=YES;
        //显示旧版评价
        // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showEvaluateView) name:SDK_ReceiveCustomerService object:nil];
        //添加下拉加载更多视图
        [self refreshHeader];
    }
    return self;
}

-(void)showEvaluateView{
    self.evaluateView.hidden=NO;
}
/**
 *  @Author lpm, 15-07-27 16:07:41
 *
 *  @brief  绘制界面
 */
-(void)drawView:(BOOL)isKefu
{
    self.backgroundColor = [TKIMColorHelper stringToColor:@"#EBECED"];
    //聊天列表
    if (isKefu) {
        _tableView = [[TKIMTableView alloc] initWithFrame:CGRectMake(0, _kefuMenu.bottom,self.width, self.height-50)];
    }else{
        _tableView = [[TKIMTableView alloc] initWithFrame:CGRectMake(0, 0,self.width,self.height)];
        [self.kefuMenu removeFromSuperview];
        [self.evaluateView  removeFromSuperview];
    }
    _tableView.delegate = self;
    _tableView.dataSource = self;
    UIView *view  = [UIView new];
    _tableView.tableFooterView = view;
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, 5)];
    _tableView.tableHeaderView = headView;
    _tableView.canCancelContentTouches = NO;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.backgroundColor = [TKIMColorHelper stringToColor:@"#EBECED"];
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    _tableView.allowsSelection = NO;
    _tableView.estimatedRowHeight = 0;
    [self addSubview:_tableView];
    ////
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIMenuControllerWillHideMenuNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuCtrlWillHide) name:UIMenuControllerWillHideMenuNotification object:nil];
    
    _toolBar = [[TKIMToolBar alloc] initWithFrame:CGRectMake(0,  _tableView.bottom, self.width, 50) toolBarType:_toolBarType];
    _toolBar.delegate = self;
    [self addSubview:_toolBar];
    
    //    [self bringSubviewToFront:self.evaluateView];
}


-(void)menuCtrlWillHide
{
    [UIMenuController sharedMenuController].menuItems  = @[];
}

-(void)Apaste:(UIMenuItem*)item{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    _toolBar.input.text = pasteboard.string;
}

-(TKIMKeFuMenuView*)kefuMenu{
    if (_kefuMenu==nil) {
        _kefuMenu=[[TKIMKeFuMenuView alloc] init];
        _kefuMenu.backgroundColor=[UIColor whiteColor];
    }
    return  _kefuMenu;
    
}

-(TKIMEvaluateView*)evaluateView{
    if (_evaluateView==nil) {
        _evaluateView=[[TKIMEvaluateView alloc] init];
        _evaluateView.backgroundColor=[UIColor clearColor];
        __weak __typeof(self) weakSelf=self;
        _evaluateView.block=^(NSInteger tag,UIButton* btn ,NSInteger errorNumber){
            __strong __typeof(self)strongSelf =weakSelf;
            if (tag==103) {
                
                if (strongSelf.evaluateView.isSpred) {
                    [UIView animateWithDuration:0.1 animations:^{
                        CGRect rect=strongSelf.evaluateView.frame;
                        strongSelf.evaluateView.frame=CGRectMake(self.width-15-44, rect.origin.y, 44, 44);
                        strongSelf.evaluateView.isSpred=NO;
                    }];
                }else{
                    CGRect rect=strongSelf.evaluateView.frame;
                    [UIView animateWithDuration:0.1 animations:^{
                        strongSelf.evaluateView.frame=CGRectMake(self.width-15-217, rect.origin.y, 217, 44);
                        strongSelf.evaluateView.isSpred=YES;
                    }];
                }
            }else{
                if (errorNumber==0) {
                    if (tag==101) {//满意
                        [strongSelf.dataSource addObject:@"您对客服进行了评价:满意"];
                        TKIMMessage *msg =  [strongSelf getMsgObject:@"感谢您对我的评价!" isSender:NO];
                        msg.attrText = [strongSelf filterTxtMessage:msg.text];
                        
                        [strongSelf.dataSource addObject:msg];
                        
                        dispatch_barrier_async(strongSelf.messageQueue, ^{
                            //                            [strongSelf.dataSource addObject:msg];
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [strongSelf.tableView reloadData];
                                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_dataSource.count-1 inSection:0];
                                _isNeedGoBootom=YES;
                                [strongSelf.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
                            });
                        });
                    }else if (tag==102){//不满意
                        [strongSelf.dataSource addObject:@"您对客服进行了评价:不满意"];
                        TKIMMessage *msg =  [strongSelf getMsgObject:@"感谢您对我的评价!" isSender:NO];
                        msg.attrText = [strongSelf filterTxtMessage:msg.text];
                        [strongSelf.dataSource addObject:msg];
                        
                        dispatch_barrier_async(strongSelf.messageQueue, ^{
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [strongSelf.tableView reloadData];
                                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_dataSource.count-1 inSection:0];
                                _isNeedGoBootom=YES;
                                [strongSelf.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
                            });
                            
                        });
                    }
                }
                
                CGRect rect=strongSelf.evaluateView.frame;
                [UIView animateWithDuration:0.1 animations:^{
                    strongSelf.evaluateView.isSpred=NO;
                    strongSelf.evaluateView.frame=CGRectMake(self.width-15-44, rect.origin.y, 44, 44);
                }];
            }
            
        };
    }
    return _evaluateView;
}

#pragma 下拉加载
//创建下拉加载更多历史数据视图
-(TKIMRefreshHeaderView *)refreshHeader
{
    __weak typeof(self) weakSelf = self;
    if (!_refreshHeader) {
        _refreshHeader = [[TKIMRefreshHeaderView alloc] initWithScrollView:weakSelf.tableView beginLoadMoreBlock:^(TKIMRefreshHeaderView * refreshHeader) {
            if([weakSelf.delegate respondsToSelector:@selector(requestMoreHistoryMessagecount:historyDataBlock:)]){
                [weakSelf.delegate requestMoreHistoryMessagecount:weakSelf.dataSource.count+15 historyDataBlock:^(NSMutableArray * historyData) {
                    _isNeedGoBootom=NO;
                    if (weakSelf.dataSource.count < historyData.count) {
                        [weakSelf reloadHistoryList:historyData];
                        refreshHeader.haveMoreHistoryData = YES;
                    }else{
                        refreshHeader.haveMoreHistoryData = NO;
                    }
                    //刷新视图停止刷新
                    [refreshHeader endRefresh];
                }];
            }
        }];
    }
    return _refreshHeader;
}


#pragma mark Table委托
/**
 *  @Author lpm, 15-07-27 16:07:06
 *
 *  @brief
 *
 *  @param tableView
 *  @param section
 *
 *  @return
 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSource.count;
}


/**
 *  @Author lpm, 15-07-27 16:07:12
 *
 *  @brief
 *
 *  @param tableView
 *  @param indexPath
 *
 *  @return
 */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row < _dataSource.count)
    {
        NSObject *obj = _dataSource[indexPath.row];
        if ([obj isKindOfClass:[NSString class]])
        {
            NSString *identifier = [NSString stringWithFormat:@"time"];
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (!cell)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
                cell.backgroundColor = [UIColor clearColor];
            }
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
            cell.textLabel.text = (NSString *)obj;
            cell.textLabel.font = [UIFont systemFontOfSize:13.0f];
            cell.textLabel.textColor = [UIColor grayColor];
            return cell;
        }else
        {
            TKIMMessage *message = (TKIMMessage *)obj;
            TKIMMsgType type =  message.type;
            
            NSString *identifier = [NSString stringWithFormat:@"MessageCell==%ld",(long)type];
            TKIMChatViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (!cell)
            {
                cell = [[TKIMChatViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier msg:message];
                cell.backgroundColor = [UIColor clearColor];
            }
            
            [cell setMessage:message];
            return cell;
        }
    }
    return nil;
}


/**
 *  @Author lpm, 15-07-27 19:07:41
 *
 *  @brief
 *
 *  @param tableView
 *  @param indexPath
 *
 *  @return
 */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row < _dataSource.count){
        NSObject *obj = _dataSource[indexPath.row];
        if (![obj isKindOfClass:[NSString class]]){
            TKIMMessage *message = (TKIMMessage *)obj;
            CGFloat height = message.size.height;
            
            if (message.type == TKIMMsgTypeScore) {
                CGFloat h =[TKIMChatViewCell heightForRow:message];
                return h;
            }else{
                if (height == 0.){
                    CGFloat h =[TKIMChatViewCell heightForRow:message];
                    return h;
                }else{
                    return message.size.height;
                }
                
            }
        }
        return 40;
    }
    return 40;
}


- (void)tableViewDidReloadData:(UITableView *)tableView{
    
    if (_dataSource.count>0&&_isNeedGoBootom)
    {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_dataSource.count-1 inSection:0];
        [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
    
}
/**
 *  @Author lpm, 15-11-19 11:11:28
 *
 *  @brief
 *
 *  @param touches
 *  @param event
 */
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self tableOnTouch];
}


/**
 *  @Author lpm, 15-11-19 11:11:28
 *
 *  @brief
 *
 *  @param touches
 *  @param event
 */
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self tableOnTouch];
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [UIView animateWithDuration:0.1 animations:^{
        self.evaluateView.isSpred=NO;
        self.evaluateView.frame=CGRectMake(self.width-15-44, self.evaluateView.frame.origin.y, 44, 44);
    }];
}

#pragma mark 工具栏代理


/**
 *  @Author lpm, 15-07-28 09:07:53
 *
 *  @brief  键盘显示
 *
 *  @param offset 偏移量
 */
-(void)keyBoardShow:(CGFloat)offset duration:(CGFloat)duration
{
    [UIView animateWithDuration:duration animations:^
     {
         self.evaluateView.hidden=YES;
         _tableView.frame = CGRectMake(_tableView.left, _tableView.top,_tableView.width, self.height-offset-50);
         if (_dataSource.count>0)
         {
             _isNeedGoBootom=YES;
             NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_dataSource.count-1 inSection:0];
             [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
         }
     }
                     completion:^(BOOL finished)
     {
         id data=[[TKIMInterfaceHelper sharedInstance] valueForKeyData:TKIMSDK_KEFU_USER_DATA];
         if (!data) {
             _evaluateView.hidden=YES;
         }else{
             self.evaluateView.hidden=NO;
         }
         [UIView animateWithDuration:0.5 animations:^
          {
              CGRect inputbarrect=self.toolBar.frame;
              CGRect rect=self.evaluateView.frame;
              rect.origin.y=(inputbarrect.origin.y-10-44);
              self.evaluateView.frame=rect;
          }];
     }];
}


/**
 *  @Author lpm, 15-07-28 09:07:12
 *
 *  @brief  键盘消失
 *
 *  @param offset 偏移量
 */
-(void)keyBoardHide:(CGFloat)offset duration:(CGFloat)duration
{
    [UIView animateWithDuration:duration animations:^
     {
         _tableView.frame = CGRectMake(_tableView.left, _tableView.top,_tableView.width, self.height-50);
         
     }];
    self.evaluateView.frame=CGRectMake(self.width-15-44, self.height-44-5-50, 44, 44);
}
/**
 *  @Author lpm, 15-07-28 18:07:41
 *
 *  @brief  接收服务器消息
 *
 *  @param msg
 */
-(void)receiveMsg:(id)msg
{
    TKIMMessage *txtMsg = (TKIMMessage *)msg;
    if (msg)
    {
        dispatch_barrier_async(_messageQueue, ^
           {
               if (txtMsg.type == TKIMMsgTypeTxt)
               {
                   txtMsg.attrText = [self filterTxtMessage:txtMsg.text];
               }
               
               [_dataSource addObject:txtMsg];
               dispatch_async(dispatch_get_main_queue(), ^ {
                   //                                       [_tableView reloadData];
                   NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_dataSource.count-1 inSection:0];
                   [_tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];
                   [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
               });
           });
    }
}

/**
 *  刷新历史记录
 *
 *  @param dataList 数据源
 *  @param row      滚动到历史消息位置
 */
-(void)reloadHistoryList:(NSMutableArray *)dataList
{
    dispatch_barrier_async(_messageQueue, ^{
        NSMutableArray *formatArray = [[NSMutableArray alloc] init];
        for (TKIMMessage *message in dataList)
        {
            NSDate *createDate = [TKIMDateHelper stringToDate:message.time];
            NSTimeInterval tempDate = [createDate timeIntervalSinceDate:self.chatTagDate];
            if (tempDate > 60 || tempDate < -60 || (self.chatTagDate == nil)) {
                [formatArray addObject:[TKIMDateHelper  formattedTime:message.time]];
                self.chatTagDate = createDate;
            }
            if (message.type == TKIMMsgTypeTxt)
            {
                message.attrText = [self filterTxtMessage:message.text];
            }
            [formatArray addObject:message];
        }
        self.dataSource = formatArray;
        
        CGFloat oldHeight = self.tableView.contentSize.height;
        dispatch_async(dispatch_get_main_queue(), ^{
            [_tableView reloadData];
            self.tableView.contentOffset = CGPointMake(0, self.tableView.contentSize.height - oldHeight);
        });
    });
}


/**
 *  @Author lpm, 15-07-28 18:07:41
 *
 *  @brief  刷新列表
 *
 *  @param msg
 */
-(void)reloadList:(NSMutableArray *)dataList isNeedTime:(BOOL)isneedtime
{
    if (dataList&&dataList.count)
    {
        dispatch_barrier_async(_messageQueue, ^{
            NSMutableArray *formatArray = [[NSMutableArray alloc] init];
            for (TKIMMessage *message in dataList)
            {
                NSDate *createDate = [TKIMDateHelper stringToDate:message.time];
                NSTimeInterval tempDate = [createDate timeIntervalSinceDate:self.chatTagDate];
                if (tempDate > 60 || tempDate < -60 || (self.chatTagDate == nil)) {
                    [formatArray addObject:[TKIMDateHelper  formattedTime:message.time]];
                    self.chatTagDate = createDate;
                }
                if (message.type == TKIMMsgTypeTxt)
                {
                    message.attrText = [self filterTxtMessage:message.text];
                }
                [formatArray addObject:message];
            }
 
            self.dataSource = formatArray;
            dispatch_async(dispatch_get_main_queue(), ^{
                [_tableView reloadData];
                if(self.dataSource.count>0)
                {
                    _isNeedGoBootom=YES;
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_dataSource.count-1 inSection:0];
                    [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
                }
            });
            
        });
    }
    else
    {
        _dataSource = [@[] mutableCopy];
        //没有数据的时候需要做一次漫游 Alan新修改
        __weak __typeof(self) weakSelf=self;
        if([weakSelf.delegate respondsToSelector:@selector(requestMoreHistoryMessagecount:historyDataBlock:)]){
            [weakSelf.delegate requestMoreHistoryMessagecount:weakSelf.dataSource.count+15 historyDataBlock:^(NSMutableArray * historyData) {
                _isNeedGoBootom=NO;
                if (weakSelf.dataSource.count < historyData.count) {
                    [weakSelf reloadHistoryList:historyData];
                    weakSelf.refreshHeader.haveMoreHistoryData = YES;
                }else{
                    weakSelf.refreshHeader.haveMoreHistoryData = NO;
                }
                
            }];
        }
        [_tableView reloadData];
    }
}

- (NSDate *)chatTagDate
{
    if (_chatTagDate == nil)
    {
        _chatTagDate = [TKIMDateHelper dateWithTimeIntervalInMilliSecondSince1970:0];
    }
    return _chatTagDate;
}

/**
 *  @Author lpm, 15-07-29 16:07:21
 *
 *  @brief  滚动时收起键盘
 *
 *  @param scrollView
 */
-(void)tableOnTouch
{
    [_toolBar resignInputFirstResponder];
    if ([UIMenuController sharedMenuController].isMenuVisible)
    {
        [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
    }
}


/**
 *  @Author lpm, 15-07-29 16:07:38
 *
 *  @brief  收起键盘
 */
-(void)resignInputFirstResponder
{
    [_toolBar resignInputFirstResponder];
}


#pragma mark 消息发送相关
/**
 *  @Author lpm, 15-10-27 09:10:48
 *
 *  @brief  路由事件
 *
 *  @param eventName 事件名
 *  @param userInfo 参数
 */
-(void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo
{
    //播放声音
    if ([eventName isEqualToString:TKIMAudioEvent]){
        [self playAudio:userInfo];
    }
    //录音
    else if([eventName isEqualToString:TKAudioRecordEvent]){
        [self recordAudio:userInfo];
    }
    //发送图片
    else if([eventName isEqualToString:TKIMImageSelectedEvent]){
        [self sendImages:(NSArray *)userInfo];
    }
    //发送声音 || 发送拍照图片
    else if([eventName isEqualToString:TKAudioSendEvent]||[eventName isEqualToString:TKIMSendPhotoEvent]){
        [self sendMessage:(TKIMMessage *)userInfo];
    }
    else if([eventName isEqualToString:TKIMSendLocationEvent]){
        [self jumpToLocationCtl];
    }
    //发送录像
    else if([eventName isEqualToString:TKIMVideoSelectedEvent]){
        [self sendVideos:(TKIMVideoMessage *)userInfo];
    }else if ([eventName isEqualToString:TKIMSendQuickReplyEvent]){//展示快捷回复
        
    }
    //长按消息
    else if ([eventName isEqualToString:TKIMMsgLongPressEvent]){
        TKIMMessage *msg = userInfo[@"msg"];
        UIView *view = userInfo[@"view"];
        [self showMenu:msg view:(TKIMBaseMsgView *)view];
    }
    //菜单工具栏事件
    else if ([eventName isEqualToString:TKIMMenuBarOnclickEvent]){
        [self menuBarOnclick:userInfo];
    }else if ([eventName isEqualToString:TKIMToScoreEvent]){
        [self doSendScore:(TKIMKeFuEvaluateView *)userInfo];
    }
    else{
        [super routerEventWithName:eventName userInfo:userInfo];
    }
}


- (UIViewController*)viewController {
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}

-(void)typeAheadText:(NSString*)text{
    [_toolBar typeAheadText:text];
}


-(void)doSendScore:(TKIMKeFuEvaluateView*)view{
    TKIMMessage * message = view.message;
    id data=[[TKIMInterfaceHelper sharedInstance] valueForKeyData:TKIMSDK_KEFU_USER_DATA];
    
    if (data) {
        NSDictionary* dict=(NSDictionary*)data;
        NSString * sessionid=dict[@"sessionid"];
        NSString * sid=dict[@"sid"];
        NSString * cid=dict[@"cid"];
        NSString * score=message.ext[@"scoreLevel"];
        NSString * describe=@"";
        NSString * spuid=dict[@"toPuid"];
        NSString * msgId=message.messageId;
        NSString * cpuid=[TKIMSDKManager getLoginUserPuid];
        
        
        [TKIMInterfaceHelper evaluationSatisfaction:sessionid sid:sid cid:cid score:score describe:describe spuid:spuid cpuid:cpuid msgId:msgId  callback:^(NSInteger errorNumber, NSString *info) {
            if (errorNumber==0) {
                TKIMChatViewCell * cell = (TKIMChatViewCell*)view.superview.superview.superview.superview;
                [cell setMessage:message];
                
                NSIndexPath *path = [_tableView indexPathForCell:cell];
                [_dataSource replaceObjectAtIndex:path.row withObject:message];
                [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:path, nil] withRowAnimation:UITableViewRowAnimationNone];
                [[TKIMDBManager shareInstance]updateMsgExt:message];
            }else{
                [[TKIMLayerUtils instance] showTip:@"评价失败!"];
            }
        }];
    }
}


/**
 *  @Author lpm, 16-05-10 11:05:39
 *
 *  @brief  播放声音
 *
 *  @param userInfo
 */
-(void)playAudio:(NSDictionary *)userInfo
{
    NSString *state = userInfo[@"state"];
    TKIMAudioMessage *audio = userInfo[@"msg"];
    TKIMAudioMsgView *msgView = userInfo[@"msgView"];
    //如果是播放
    if ([state isEqualToString:@"play"])
    {
        //先停止当前播放的声音
        if (_currentAudio)
        {
            [_audioHelper stopPlay];
            [_currentAudio stopPlaying];
        }
        _currentAudio = msgView;
        [_audioHelper play:[NSURL fileURLWithPath:audio.localUrl]];
    }
    else
    {
        [_audioHelper stopPlay];
        _currentAudio = nil;
    }
}


/**
 *  @Author lpm, 16-05-10 11:05:00
 *
 *  @brief  录音
 *
 *  @param userInfo
 */
-(void)recordAudio:(NSDictionary *)userInfo
{
    //先停止当前播放的声音
    if (_currentAudio)
    {
        [_audioHelper stopPlay];
        [_currentAudio stopPlaying];
    }
}


/**
 *  @Author lpm, 16-05-10 11:05:25
 *
 *  @brief  菜单被点击
 *
 *  @param userInfo
 */
-(void)menuBarOnclick:(NSDictionary *)userInfo
{
    TKIMMessage *msg = [[TKIMMessage alloc] init];
    msg.text = (NSString *)userInfo;
    msg.isOrder = YES;
    msg.isSender = YES;
    [self sendMessage:msg];
    [self tip];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tip removeFromSuperview];
    });
}

/**
 *  @Author lpm, 16-01-08 19:01:06
 *
 *  @brief  跳转到定位的控制器
 */
-(void)jumpToLocationCtl
{
    [self routerEventWithName:TKIMLocationClickEvent userInfo:nil];
}


/**
 *  @Author lpm, 15-10-27 15:10:23
 *
 *  @brief  发送位置
 *
 *  @param location
 */
-(void)sendLocation:(TKIMLocationMessage *)location
{
    location.isSender = YES;
    [self sendMessage:(TKIMMessage *)location];
}

/**
 *  @Author lpm, 15-10-21 17:10:40
 *
 *  @brief  长按单元格
 *
 *  @param tap
 */
-(void)showMenu:(TKIMMessage *)msg view:(TKIMBaseMsgView *)view
{
    if (msg.state == TKIMMsgSendStateSending)
    {
        return;
    }
    
    _selectMessage = msg;
    
    [view becomeFirstResponder];
    
    UIMenuController *menuCtrl = [UIMenuController sharedMenuController];
    [menuCtrl setTargetRect:view.backgroundImageView.frame inView:view];
    
    if (msg.state == TKIMMsgSendStateSendFail)
    {
        UIMenuItem *delete = [[UIMenuItem alloc] initWithTitle:@"删除" action:@selector(deleteMsg:)];
        UIMenuItem *reSend = [[UIMenuItem alloc] initWithTitle:@"重发" action:@selector(reSend:)];
        [menuCtrl setMenuItems:@[delete,reSend]];
    }
    else
    {
        UIMenuItem *delete = [[UIMenuItem alloc] initWithTitle:@"删除" action:@selector(deleteMsg:)];
        UIMenuItem *copy = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyMsg:)];
        
        if (msg.type == TKIMMsgTypeTxt)
        {
            [menuCtrl setMenuItems:@[delete,copy]];
        }
        else
        {
            [menuCtrl setMenuItems:@[delete]];
        }
    }
    
    [menuCtrl setMenuVisible:YES animated:YES];
}


/**
 *  @Author lpm, 15-11-19 11:11:54
 *
 *  @brief  复制
 *
 *  @param sender
 */
- (void)copyMsg:(id)sender
{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    if (_selectMessage) {
        pasteboard.string = _selectMessage.text;
    }
    _selectMessage = nil;
}


/**
 *  @Author lpm, 15-11-19 11:11:13
 *
 *  @brief  删除消息
 *
 *  @param item
 */
-(void)deleteMsg:(UIMenuItem *)item
{
//    [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
//    [[TKIMManager shareInstance] removeMessage:_selectMessage];
//    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[_dataSource indexOfObject:_selectMessage] inSection:0];
//    [_dataSource removeObject:_selectMessage];
//    //    [_tableView beginUpdates];
//    [_tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
//    //    [_tableView endUpdates];
//    _selectMessage = nil;

    
    
    [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
    [[TKIMManager shareInstance] removeMessage:_selectMessage];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[_dataSource indexOfObject:_selectMessage] inSection:0];
    NSMutableArray *indexPathArr = [[NSMutableArray alloc]init];
    [indexPathArr addObject:indexPath];
    
    NSInteger row = indexPath.row;
    NSInteger dataSourceCount = _dataSource.count - 1;
    if (row < dataSourceCount) {
        if ( ([_dataSource[row-1] isKindOfClass:[NSString class]]) &&
             ([_dataSource[row+1] isKindOfClass:[NSString class]])  ) {
            NSIndexPath *timeIndexPath = [NSIndexPath indexPathForRow:row-1 inSection:0];
            [indexPathArr addObject:timeIndexPath];
            [_dataSource removeObjectAtIndex:row-1];
        }
    }else if (row == dataSourceCount){
        if ([_dataSource[row-1] isKindOfClass:[NSString class]]) {
            NSIndexPath *timeIndexPath = [NSIndexPath indexPathForRow:row-1 inSection:0];
            [indexPathArr addObject:timeIndexPath];
            [_dataSource removeObjectAtIndex:row-1];
        }
    }
    
    [_dataSource removeObject:_selectMessage];
    [_tableView deleteRowsAtIndexPaths:indexPathArr withRowAnimation:UITableViewRowAnimationFade];
    _selectMessage = nil;
}


/**
 *  @Author lpm, 15-11-19 11:11:13
 *
 *  @brief  重发消息
 *
 *  @param item
 */
-(void)reSend:(UIMenuItem *)item
{
    _selectMessage.state = TKIMMsgSendStateSending;
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[_dataSource indexOfObject:_selectMessage] inSection:0];
    [_tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    [[TKIMManager shareInstance] resendMessage:_selectMessage];
    _selectMessage = nil;
}


/**
 *  @Author lpm, 15-11-19 11:11:44
 *
 *  @brief  放行响应事件
 *
 *  @param action
 *  @param sender
 *
 *  @return
 */
-(BOOL) canPerformAction:(SEL)action withSender:(id)sender{
    if (action == @selector(deleteMsg:)||action == @selector(reSend:)||action == @selector(copyMsg:)) {
        return YES;
    }
    return NO; //隐藏系统默认的菜单项
}


/**
 *  @Author lpm, 15-07-27 16:07:21
 *
 *  @brief  发送消息
 *
 *  @param message
 */
-(void)sendTxt:(NSString *)message
{
    TKIMMessage *msg =  [self getMsgObject:message isSender:YES];
    msg.attrText = [self filterTxtMessage:msg.text];
    [self sendMessage:msg];
}


/**
 *  @Author lpm, 15-10-22 20:10:27
 *
 *  @brief  发送图片
 *
 *  @param images
 */
-(void)sendImages:(NSArray *)images
{
    [images enumerateObjectsUsingBlock:^(id  obj, NSUInteger idx, BOOL *  stop)
     {
         TKIMPhotoModel *photo = (TKIMPhotoModel *)obj;
         TKIMImageMessage *msg = [[TKIMImageMessage alloc] init];
         msg.isSender = YES;
         msg.thumbImage = photo.thumbImage;
         msg.originImage = photo.originImage;
         [self sendMessage:msg];
     }];
}


/**
 *  @Author lpm, 15-10-23 10:10:33
 *
 *  @brief  发消息
 *
 *  @param msg
 */
-(void)sendVideos:(TKIMVideoMessage *)video
{
    [self sendMessage:video];
}


/**
 *  @Author lpm, 15-07-29 10:07:04
 *
 *  @brief  发送系统消息
 *
 *  @param message
 */
-(void)sendSysMsg:(NSString *)message
{
    dispatch_barrier_async(_messageQueue, ^{
        [_dataSource addObject:[self getMsgObject:message isSender:NO]];
        dispatch_async(dispatch_get_main_queue(), ^{
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_dataSource.count-1 inSection:0];
            [_tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            _isNeedGoBootom=YES;
            [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        });
    });
}


/**
 *  @Author lpm, 15-10-23 10:10:33
 *
 *  @brief  发消息
 *
 *  @param msg
 */
-(void)sendMessage:(TKIMMessage *)msg
{
    if (_delegate && [_delegate respondsToSelector:@selector(sendMessage:)])
    {
        [_delegate sendMessage:msg];
    }
    
    if (!msg.isOrder)
    {
        msg.fromUser = [TKIMSDKHelper getLoginUserName];
        //        dispatch_barrier_async(_messageQueue, ^{
        //
        //            dispatch_async(dispatch_get_main_queue(), ^{
        //               [_tableView beginUpdates];
        //
        //                [_dataSource addObject:msg];
        //                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_dataSource.count-1 inSection:0];
        //                _isNeedGoBootom=YES;
        //                [_tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        //
        //                [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        //                [_tableView endUpdates];
        //            });
        //
        //        });
        
        dispatch_barrier_async(_messageQueue, ^{
            [_dataSource addObject:msg];
            dispatch_async(dispatch_get_main_queue(), ^{
                [_tableView reloadData];
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_dataSource.count-1 inSection:0];
                [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
            });
        });
    }
}



/**
 *  @Author lpm, 15-07-28 18:07:41
 *
 *  @brief  更新消息状态
 *
 *  @param msg
 */
-(void)updateMsg:(TKIMMessage *)message
{
    //    NSLog(@"update");
    if (message)
    {
        dispatch_barrier_async(_messageQueue, ^ {
            for (NSObject *obj in _dataSource)
            {
                if (![obj isKindOfClass:[NSString class]])
                {
                    NSInteger index = [_dataSource indexOfObject:obj];
                    TKIMMessage *msg = (TKIMMessage *)obj;
                    
                    if ([message.messageId isEqualToString:msg.messageId])
                    {
                        message.size = msg.size;
                        
                        if (message.type == TKIMMsgTypeTxt)
                        {
                            message.attrText = [self filterTxtMessage:message.text];
                        }
                        
                        [_dataSource replaceObjectAtIndex:index withObject:message];
                        
                        dispatch_async(dispatch_get_main_queue(), ^
                           {
                               // [_tableView reloadData];//把刷新整个tableview改为刷新一行
                               NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
                               [_tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                           });
                        break;
                    }
                }
            }
        });
    }
}

/**
 *  @Author lpm, 15-07-29 10:07:21
 *
 *  @brief  发送消息s
 *
 *  @param message  消息
 *  @param userType 用户类型
 */
-(TKIMMessage *)getMsgObject:(NSString *)message isSender:(BOOL)isSender
{
    TKIMMessage *msg = [[TKIMMessage alloc] init];
    msg.text = message;
    msg.isSender = isSender;
    return msg;
}


/**
 *  @Author lpm, 15-10-27 09:10:14
 *
 *  @brief  播放完成
 *
 *  @param flag 是否播放成功
 */
-(void)audioPlayerDidFinishPlaying:(BOOL)flag
{
    if (_currentAudio)
    {
        [_currentAudio stopPlaying];
        _currentAudio = nil;
    }
}


#pragma mark 文本消息过滤

/**
 *  @Author lpm, 15-12-04 14:12:15
 *
 *  @brief  表情
 *
 *  @return
 */
-(NSDictionary *)emotion
{
    if (!_emotion)
    {
        NSString *emotionPlist = TKIMSrcName(@"TKIMEmotion.json");
        NSData *data = [NSData dataWithContentsOfFile:emotionPlist];
        NSDictionary *dic = (NSDictionary *)[TKIMDataHelper dataToObject:data];
        _emotion = dic[@"emotion"];
    }
    return _emotion;
}



/**
 *  @Author lpm, 15-12-04 14:12:23
 *
 *  @brief  过滤文字消息
 *
 *  @param text
 *
 *  @return
 */
-(NSAttributedString *)filterTxtMessage:(NSString *)text
{
    return [self filterTxtMessage:text font:15 imageBounds:CGRectMake(0, -6, 25,25)];
}
/**
 *  @Author lpm, 15-12-04 14:12:23
 *
 *  @brief  过滤文字消息
 *
 *  @param text
 *
 *  @return
 */
-(NSAttributedString *)filterTxtMessage:(NSString *)text font:(CGFloat)f imageBounds:(CGRect)bounds
{
    if (!text || ![text isKindOfClass:[NSString class]]){
        return nil;
    }
    NSString *emotionPlist = TKIMSrcName(@"TKIMEmotion.json");
    NSData *data = [NSData dataWithContentsOfFile:emotionPlist];
    NSDictionary *dic = (NSDictionary *)[TKIMDataHelper dataToObject:data];
    NSDictionary *emotion = dic[@"emotion"];
    
    NSMutableArray *textArray = [NSMutableArray array];
    NSMutableArray *imgArray = [NSMutableArray array];
    
    NSRange range = [text rangeOfString:@"["];
    if (range.location != NSNotFound){
        NSDictionary *userInfo =  [TKIMStringHelper replaceString:text from:@"\\[@emoji_\\d+\\.gif\\]" to:@"┠┨" ];
        NSString *textCopy = userInfo[@"replaceString"];
        textArray = (NSMutableArray *)[textCopy componentsSeparatedByString:@"┠┨"];
        NSArray *ts =  userInfo[@"matchResults"];
        if (emotion){
            //遍历消息文字数组
            for (NSString *value in ts){
                NSString *imageName = emotion[value];
                if (imageName){
                    [imgArray addObject:imageName];
                }
            }
        }
    }
    
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] init];
    
    if (imgArray && imgArray.count == 0){
        NSAttributedString *substr =[[NSAttributedString alloc] initWithString:text];
        [attributedText appendAttributedString:substr];
    }else{
        for (NSUInteger i = 0; i < textArray.count; i++){
            NSAttributedString *substr =[[NSAttributedString alloc] initWithString:[textArray objectAtIndex:i]];
            [attributedText appendAttributedString:substr];
            if (i != textArray.count - 1){
                NSTextAttachment *attch = [[NSTextAttachment alloc] init];
                NSInteger count = imgArray.count -1;
                if(count < i){
                    continue;
                }
                
                NSString* url = [NSString stringWithFormat:@"%@", imgArray[i]];
                NSString* imgUrl = TKIMSrcName(url);
                NSString* str = [[[imgUrl componentsSeparatedByString:@"/"] lastObject] componentsSeparatedByString:@"."][0];
                NSString* x = [NSString stringWithFormat:@"TKIMSDKAssets.bundle/%@", str];
                UIImage* image = [UIImage imageNamed:x];
                attch.bounds = bounds;
                attch.image = image;
                [attch.image  setAccessibilityIdentifier:url];
                NSAttributedString *substr2 = [NSAttributedString attributedStringWithAttachment:attch];
                [attributedText appendAttributedString:substr2];
            }
        }
    }
    
    //给文字中的链接做标记
    //    [TKIMAttributedLabelURL detectLinks:attributedText];
    
    // 一定要设置字体,保证计算出来的尺寸是正确的
    UIFont *font = [UIFont systemFontOfSize:f];
    [attributedText addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, attributedText.length)];
    return attributedText;
}

#pragma mark 属性
-(TKIMAcceptOrderTip *)tip
{
    if (!_tip) {
        TKIMAcceptOrderTip * tip = [[TKIMAcceptOrderTip alloc] initWithFrame:CGRectMake((self.width-150)*0.5, self.height-50-35-15, 150, 35)];
        _tip = tip;
        [self addSubview:_tip];
        [self bringSubviewToFront:_tip];
    }
    return _tip;
}


-(void)setMenusArray:(NSArray *)menusArray
{
    _menusArray = menusArray;
    self.toolBar.menusArray = menusArray;
    if(menusArray.count >0)
    {
        self.toolBar.tooBarType = TKIMToolBarOfiicalType;
    }
}
-(void)dealloc
{
    [self.toolBar removeCss];
}

@end
